// Client.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "Client.h"

CConnectSocket connectSocket;

BOOL CALLBACK	MainDlgProc(HWND, UINT, WPARAM, LPARAM);
int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	DialogBox(GetModuleHandle(NULL),
			MAKEINTRESOURCE(ID_MAINDLG),
			NULL,
			(DLGPROC)MainDlgProc);
	return 0;
}

BOOL CALLBACK	MainDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) {
	
	switch(uMsg) {
		case WM_INITDIALOG:
			OnInitdialog(hDlg);
			break;
		case WM_CLOSE:
			OnClose(hDlg);
			break;
		case WM_COMMAND:
			OnCommand(hDlg, wParam, lParam);
			break;
	}
	return 0;
};

void OnInitdialog(HWND hDlg) {
	if (!WndSocketStartup())
		MessageBox(hDlg, TEXT("Startup window socket fail"), TEXT("Error"), MB_OK);
} 
void OnClose(HWND hDlg) {
	WndSocketCleanup();
	EndDialog(hDlg, 0);
}
void OnCommand(HWND hDlg, WPARAM wParam, LPARAM lParam) {
	switch(LOWORD(wParam)) {
		case ID_START:
			{
				EnableWindow(GetDlgItem(hDlg, ID_START), FALSE);
				if (connectSocket.Connect("localhost", "12345"))
					MessageBox(hDlg, TEXT("Connect succuessfulyy"), TEXT("Information"), MB_OK | MB_ICONINFORMATION);
				else {
					MessageBox(hDlg, TEXT("Connect fail"), TEXT("Error"), MB_OK | MB_ICONERROR);
					EnableWindow(GetDlgItem(hDlg, ID_START), TRUE);
				}
			}
			break;
		case ID_SEND:
			{
				const int MAXSIZE = 521;
				size_t nByte;
				int size;
				TCHAR szBuffer[MAXSIZE];
				ZeroMemory(szBuffer, MAXSIZE);
				GetWindowText(GetDlgItem(hDlg, ID_EBOX), szBuffer, MAXSIZE);
				StringCbLength(szBuffer, MAXSIZE, &nByte);
				size = (int)nByte;
				SetWindowText(GetDlgItem(hDlg, ID_EBOX), NULL);
				SetFocus(GetDlgItem(hDlg, ID_EBOX));
				connectSocket.Send(&size, sizeof(int));
				connectSocket.Send(szBuffer, size);
			}
			break;
	}
}